const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        farmerId: "",
        allChecked: false,
        showPriceInput: false,
        showPriceConfirm: false,
        unitPrice: "",
        managementFee: "",
        showBookPicker: false,
        bookList: [],
        syncOrderItem: {},
        selectedOrderList: [],
        openPriceInfo: {},
        qualityMap: {
            1: "精品",
            2: "次品",
            3: "统货"
        },
        orderList: [],
        show: false,
        startTime: "",
        endTime: "",
        minDate: new Date(2021, 0, 1).getTime(),
        maxDate: new Date().getTime(),
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.id) {
            this.setData({
                farmerId: options.id
            })
        } else {
            this.setData({
                farmerId: ""
            })
        }
        this.getBookData()
    },
    onShow: function () {
        this.reset()
        this.getData()
    },
    reset: function () {
        this.setData({
            orderList: [],
            allChecked: false,
            unitPrice: "",
            managementFee: "",
            startTime: "",
            endTime: "",
            selectedOrderList: [],
            openPriceInfo: {},
        })
    },
    onDisplay() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    onConfirm(event) {
        this.reset();
        const [start, end] = event.detail;
        this.setData({
            show: false,
            startTime: this.formatDate(start),
            endTime: this.formatDate(end)
        });
        this.getData();
    },
    formatDate(date = new Date()) {
        return wx.$dayjs(date).format("YYYY/MM/DD");
    },
    onPullDownRefresh() {
        this.reset()
        this.getData()
    },
    getData: function () {
        const {
            startTime,
            endTime
        } = this.data;
        let createStartTime = startTime ? wx.$dayjs(startTime).format("YYYY-MM-DD") + " 00:00:00" : "";
        let createEndTime = endTime ? wx.$dayjs(endTime).format("YYYY-MM-DD") + " 23:59:59" : "";
        let params = {
            current: 1,
            size: 100,
            createStartTime,
            createEndTime,
            enterStockStatus: 2,
            companyId: app.globalData.userInfo.companyData.companyId,
            farmerUserId: this.data.farmerId
        }
        wx.showLoading({
            title: "正在请求数据中"
        })
        wx.$apis.getMarketList(params).then(res => {
            wx.stopPullDownRefresh();
            let orderList = res.data && res.data.records.map(item => {
                item.createTimeStr = item.createTime.replace("T", " ")
                item.farmerMobile = item.farmerMobile && wx.$getMobile(item.farmerMobile)
                return item
            })
            this.setData({
                orderList: orderList
            })
        })
    },
    onChange: function (event) {
        let index = event.currentTarget.dataset.index
        let orderList = this.data.orderList;
        orderList[index].checked = !orderList[index].checked
        let allChecked = true;
        if (orderList && orderList.length) {
            orderList.forEach(item => {
                if (!item.checked) {
                    allChecked = false
                }
            });
        } else {
            allChecked = false
        }
        this.setData({
            orderList: orderList,
            allChecked: allChecked
        })
    },
    checkAll: function (event) {
        let orderList = this.data.orderList;
        if (event.detail) {
            orderList.forEach(item => {
                item.checked = true
            });
        } else {
            orderList.forEach(item => {
                item.checked = false
            });
        }
        this.setData({
            orderList: orderList,
            allChecked: event.detail
        });
    },
    getBookData() {
        wx.$apis.getAccountBookEasy().then(res => {
            let bookList = res.data && res.data.map(item => {
                item.text = item.name
                return item
            })
            this.setData({
                bookList: bookList
            })
        })
    },
    syncToAccountBook(e) {
        let item = e.currentTarget.dataset.item
        this.setData({
            syncOrderItem: item,
            showBookPicker: true
        })
    },
    onBookCancel() {
        this.setData({
            syncOrderItem: {},
            showBookPicker: false
        })
    },
    onBookConfirm(event) {
        const {
            value
        } = event.detail;
        let params = {
            accountBookId: value.id,
            financeName: "买菜",
            recordTime: wx.$dayjs().format("YYYY-MM-DD HH:mm:ss"),
            orderType: 2,
            orderId: this.data.syncOrderItem.id,
            type: 1,
        }
        wx.showLoading({
            title: "正在同步"
        })
        wx.$apis.addAccountBookRecord(params).then(res => {
            this.setData({
                showBookPicker: false
            })
            wx.showToast({
                title: '同步完成！',
                icon: 'success',
                duration: 1500
            })
            this.reset()
            this.getData()
        })
    },
    toDetail(e) {
        let item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: `/pages/business/details/index?id=${item.id}`,
        })
    },
    openPrice() {
        let orderList = this.data.orderList;
        let selectedOrderList = orderList.filter(item => item.checked)
        if (selectedOrderList && selectedOrderList.length) {
            this.setData({
                showPriceInput: true,
                unitPrice: "",
                selectedOrderList: selectedOrderList
            })
        } else {
            wx.showToast({
                title: "请勾选订单",
                icon: 'none',
                duration: 2000
            })
        }
    },
    hideInput() {
        this.setData({
            showPriceInput: false,
            unitPrice: "",
            managementFee: "",
            openPriceInfo: {},
        })
    },
    submitPrice() {
        if (!this.data.unitPrice) {
            wx.showToast({
                title: "请输入单价",
                icon: 'none',
                duration: 2000
            })
            return
        }
        let cropName = Array.from(new Set(this.data.selectedOrderList.map(item => item.cropName))).join(",")
        let openPriceInfo = {
            farmerName: this.data.selectedOrderList[0].farmerName,
            farmerMobile: this.data.selectedOrderList[0].farmerMobile,
            cropName: cropName,
            orderNumber: this.data.selectedOrderList.length,
            unitPrice: this.data.unitPrice,
            managementFee: this.data.managementFee
        }
        this.setData({
            showPriceInput: false,
            openPriceInfo: openPriceInfo,
            showPriceConfirm: true
        })
    },
    cancelPrice() {
        this.hideInput()
    },
    hideConfirm() {
        this.setData({
            showPriceConfirm: false,
            unitPrice: "",
            managementFee: "",
            openPriceInfo: {},
        })
    },
    cancelConfirm() {
        this.hideConfirm()
    },
    submitConfirm() {
        let selectedIds = this.data.selectedOrderList.map(item => item.id);
        let params = {
            companyId: app.globalData.userInfo.companyData.companyId,
            transactionPrice: Math.round(this.data.unitPrice * 100),
            managementFee: Math.round(this.data.managementFee * 100),
            id: selectedIds
        }
        wx.showLoading({
            title: "正在请求数据中"
        })
        wx.$apis.quotedOrder(params).then(res => {
            wx.showToast({
                title: "开价成功",
                icon: 'none',
                duration: 2000
            })
            wx.setStorage({
                key: "back",
                data: true,
                success: function () {
                    wx.navigateBack(); //返回上一个页面
                }
            })
        })
        this.hideConfirm()
    },
})